<?php

namespace app\admin\controller\course;

use app\common\controller\Backend;
use \app\admin\model\teacher\Teacher;
use think\Db;

/**
 * 录播课管理
 *
 * @icon fa fa-circle-o
 */
class Course extends Backend
{
    /**
     * Course模型对象
     * @var \app\admin\model\course\Course
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\course\Course;
        $this->view->assign("tags", $this->get_tags_list());
        $this->view->assign("teacherList", $this->get_teacher_list());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where(array('status' => array('NEQ', 9)))
                ->order($sort, $order)
                ->paginate($limit);

            if($list){
                foreach($list as $key=>$val){
                    $list[$key]['class_name'] = model("\app\admin\model\allclass\Allclass")->get_class_name($val['classid']);
                    if(!empty($val['tags'])){
                        $list[$key]['tags'] = model("\app\admin\model\allclass\Tags")->get_tags($val['tags']);
                    }
                }
            }
            
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // 标签处理
                    if(array_key_exists('tags',$params)){
                        $tags = $params['tags'];
                        unset($params['tags']);
                        $str = '';
                        for($i=0;$i<count($tags);$i++){
                            $str .= '#'.$tags[$i].'#,';
                            
                        }
                        $params['tags'] = rtrim($str, ",");
                    }
                    // 标签处理
                    $params['createtime'] = time();                
                    $result = $this->model->allowField(true)->insertGetId($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $row->tags = str_replace("#","",$row->tags);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    // 标签处理
                    if(array_key_exists('tags',$params)){
                        $tags = $params['tags'];
                        unset($params['tags']);
                        $str = '';
                        for($i=0;$i<count($tags);$i++){
                            $str .= '#'.$tags[$i].'#,';
                            
                        }
                        $params['tags'] = rtrim($str, ",");
                    }
                    // 标签处理
                    $params['updatetime'] = time();   
                    
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->model->where('id', $ids)->update(['status' => '9']);
        $this->success();
    }


    /**
     * 获取标签列表
     */
    public function get_tags_list()
    {
        $list = collection(model("\app\admin\model\allclass\Tags")->column('name','id'))->toArray();
        return $list;
    }

    public function get_teacher_list()
    {
        $list = collection((new Teacher())->where('status',0)->select())->toArray();
        return $list;
    }

}
